package com.ssmk.module.home.view;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.provider.Settings;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.example.retrofitlibrary.BaseObserBean;
import com.example.retrofitlibrary.RetrofitClientUtlis;
import com.ssmk.R;
import com.ssmk.bean.NfcBean;
import com.ssmk.nfc.Ntag21X;
import com.ssmk.url.Url;

import java.util.HashMap;

import io.reactivex.annotations.NonNull;

/**
 * 防伪查询页面
 */
public class Home_NFC_activity extends Activity {


    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;

    //
    private byte writeAddr = (byte)0x25;
    private byte [] writeData = {(byte)0x7E,(byte)0x7E,(byte)0x8F,(byte)0x8F};
    private byte[] readAddr = {(byte)0x00,(byte)0x20,(byte)0x28,(byte)0x2F};
    private byte [] pwd = {(byte)0x00,(byte)0x01,(byte)0x02,(byte)0x03};//page 43 0x2b
    private byte [] mirror = {(byte)0x04,(byte)0x00,(byte)0x00,(byte)0x00};//page 41 0x29
    private byte [] access = {(byte)0x14,(byte)0x00,(byte)0x00,(byte)0x00};//page 42 0x2a
    private byte [] pack ={(byte)0x7E,(byte)0x7E,(byte)0x00,(byte)0x00};//page 44  0x2c
    private byte [] new_pwd ={(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00};//page 43 0x2b
    private byte [] new_mirror = {(byte)0x04,(byte)0x00,(byte)0x00,(byte)0xFF};//page 41 0x29
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home__nfc);
        iniView();//初始化布局
        mAdapter = NfcAdapter.getDefaultAdapter(this);//获取系统NFC Adapter
        checkNFC();//初始化nfc模块


        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        // 设置 intent filter
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        try {
            ndef.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        mFilters = new IntentFilter[] { ndef, };
        mTechLists = new String[][] { new String[] { MifareClassic.class
                .getName() } , new String[] {NfcA.class.getName()}};


        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction()))
        {

            testWRNtag21x(getIntent());

        }


    }


    private void testPWDNtag21x(Intent intent) {

        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Ntag21X ntag = new Ntag21X(tag);
        //璁剧疆瀵嗙爜
        ntag.ntagConnect();
        byte [] write_pwd=ntag.writePage((byte)0x2b, pwd);//鍐欏叆瀵嗙爜
        byte[] wtite_pack =ntag.writePage((byte)0x2c,pack);//鍐欏叆PACK
        byte [] write_conf=ntag.writePage((byte)0x29,mirror);//鍐欏叆閰嶇疆椤�
        byte[] data_00_03=ntag.readFourPages(readAddr[0]);//璇诲彇鑺墖鏁版嵁
        byte [] write_result=ntag.writePage(writeAddr, writeData);//鍐欐暟鎹繘鍏ヨ姱鐗囷紝澶辫触
        String Auth=ntag.ntagAuth(pwd,new byte[]{pack[0],pack[1]});//鑾峰彇璁よ瘉
        byte [] write_result_Auth=ntag.writePage(writeAddr, writeData);//鍐欐暟鎹繘鍏ヨ姱鐗囷紝澶辫触
        byte [] write_Npwd=ntag.writePage((byte)0x2b, new_pwd);//淇敼瀵嗙爜
        byte [] write_Nconf=ntag.writePage((byte)0x29,new_mirror);//鍐欏叆鏂伴厤缃〉锛屽彇娑堝瘑鐮�
        ntag.ntagClose();
        String[]  listString = new String[8];
        listString[0] = ntag.hex2Str(write_pwd);
        listString[1] = ntag.hex2Str(write_conf);
        listString[2] = ntag.hex2Str(data_00_03);
        listString[3] = ntag.hex2Str(write_result);
        listString[4] = ntag.hex2Str(wtite_pack);
        listString[5] = ntag.hex2Str(write_result_Auth);
        listString[6] = ntag.hex2Str(write_Npwd);
        listString[7] = ntag.hex2Str(write_Nconf);
        Toast.makeText(getApplicationContext(), Auth,
                Toast.LENGTH_SHORT).show();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (this,R.layout.array_items,listString);
        LogUtils.e("nfc=","nfc"+listString);



      //  Listview_Data_List.setAdapter(adapter);
//		Listview_Data_List.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,listString));
    }


    private void testWRNtag21x(Intent intent) {
        // TODO Auto-generated method stub
        byte ReadAddr =0x00;
        String[]  listString = new String[5];
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Ntag21X ntag = new Ntag21X(tag);
        //test Read
        ntag.ntagConnect();
        for (int i = 0;i<5;i++)
        {
            byte[] NFCData = ntag.readFourPages(ReadAddr);//读取前4页
            listString[i] = hex2Str(NFCData);
            ReadAddr =(byte)(ReadAddr+(byte)0x04);
        }
        ntag.ntagClose();

        ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (this,R.layout.array_items,listString);

        HashMap<String, String> map = new HashMap<>();
        map.put("chipId",listString[1]);
        RetrofitClientUtlis.getInstance(this, Url.BASEURL).createBaseApi().post("shopsNFC/getShopsNFC.do", new BaseObserBean<NfcBean>(this)  {

            @Override
            public void onNext(@NonNull NfcBean nfcBean) {
                int code = nfcBean.getCode();
                if(code==200){
                    WebView webview=new WebView(Home_NFC_activity.this);
                    webview.loadUrl("https://www.baidu.com/");
                }
            }
        });

    }

    private  byte[] subBytes(byte[] src, int begin, int count)
    {
        byte[] bs = new byte[count];
        for (int i=begin; i<begin+count; i++)
        {
            bs[i-begin] = src[i];
        }
        return bs;
    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (mAdapter!=null && (!mAdapter.isEnabled())) {
            Toast.makeText(getApplicationContext(), "请在系统设置中先启用NFC功能",
                    Toast.LENGTH_SHORT).show();
        }

        if (mAdapter!=null) {
            mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
                    mTechLists);
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub

        testWRNtag21x(intent);

    }


    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        if (mAdapter!=null){
            mAdapter.disableForegroundDispatch(this);
        }
    }


    private void checkNFC() {
        // TODO Auto-generated method stub
        if(mAdapter == null)
        {
            Toast.makeText(getApplicationContext(), "设备不支持NFC！",
                    Toast.LENGTH_SHORT).show();
        }
        else
        {
            if(!mAdapter.isEnabled())
            {
                Toast.makeText(getApplicationContext(), "请在系统设置中先启用NFC功能！",
                        Toast.LENGTH_SHORT).show();
                startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
            }
        }
    }

    private void iniView() {
        // TODO Auto-generated method stub

    }

    public String  hex2Str(byte[] data)
    {
        String results = "";
        String hex="";
        for(int i=0;i<data.length;i++)
        {
            hex = Integer.toHexString(data[i] & 0xFF);
            if (hex.length() == 1)
            {
                hex='0' + hex;
            }
            results = results+hex;
        }
        return results;
    }
}
